<template>
  <div class="monitoring h100">
    <div class="monitoringLeft">
      <div class="topTitle">
        <div class="monitoringTitle">实时数据</div>
      </div>
      <div class="tableContent">
        <listTableNew v-bind="actualSeting" ref="klTable"></listTableNew>
      </div>
    </div>
    <div class="monitoringRight">
      <div class="topTitle">
        <div class="monitoringTitle">历史数据</div>
      </div>
      <div class="content">
        <div class="lineConditions">
          <span class="chooseTime">
            时间范围：
            <el-button
              class="el-button--plain"
              :class="{ active: changeTimeBtn == '1' }"
              size="mini"
              @click="changeTime(1)"
              >1天</el-button
            >
            <el-button
              class="el-button--plain"
              :class="{ active: changeTimeBtn == '3' }"
              size="mini"
              @click="changeTime(3)"
              >3天</el-button
            >
            <el-button
              class="el-button--plain"
              :class="{ active: changeTimeBtn == '7' }"
              size="mini"
              @click="changeTime(7)"
              >7天</el-button
            >
          </span>

          <div class="customTimeDiv">
            <span class="demonstration">自定义：</span>
            <el-date-picker
              v-model="customTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="changeCustomTime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </div>
        </div>
        <div id="historyLine" class="historyLine w100"></div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getYCHistoryApi,
  getYCRealTimeApi,
} from "@/api/orderManagement/monitoring";
export default {
  props: {
    currentNode: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  watch: {
    currentNode: {
      handler: function (newVal, oldVal) {
        this.currentDevice = Object.assign({}, newVal);
        setTimeout(() => {
          if (oldVal) {
            this.init();
          }
        }, 0);
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      type:"hour",
      userInfo: this.$store.getters.userInfo,
      currentAppInfo: this.$store.getters.currentAppInfo,
      currentDevice: {},
      historyStartTime: "",
      historyEndTime: "",
      changeTimeBtn: "1",
      customTime: [],
      currentLine: {},
      actualSeting: {
        selectionShow: false,
        radioShow: true,
        showCustomBtn: false,
        showFilterBtn: false,
        showPagination: false,
        rowKey:"code",
        pageConfig: {},
        searchObj: {
          searchMethod: (params, sortStr) => {
            this.getTableData(params, sortStr);
          },
          queryData: {
            page: 1,
            pageSize: 15,
          },
          searchArr: [
            {
              type: "input",
              label: "参数名",
              model: "name",
            },
          ],
        },
        actionList: [],
        column: [
          {
            label: "参数名",
            prop: "name",
            type: "text",
          },
          {
            label: "参数值",
            prop: "value",
            type: "text",
            width: 120,
          },
          {
            label: "单位",
            prop: "unit",
            type: "text",
            width: 90,
          },
          {
            label: "时间",
            prop: "time",
            type: "text",
            width: 160,
          },
        ],
        //表格方法
        tableMethods: {
          //点击行的方法
          rowClick: (val) => {
            this.$refs.klTable.radioSelect(val);
            this.currentLine = val;
            this.getLineData();
          },
        },
      },
      historyOption: {
        xAxis: {
          type: "category",
        },
        yAxis: {
          type: "value",
          name: "单位：",
          axisLine: {
            show: true,
          },
        },
        tooltip: {
          trigger: "axis",
          textStyle: {
            align: "left",
          },
          formatter: function (params) {
            let item = params[0];
            let value = item.value;
            let result =
              value.key +
              "<br/>时间：" +
              value.time +
              "<br/>数值：" +
              value.value;
            return result;
          },
        },
        series: [
          {
            type: "line",
            showSymbol: false,
            markArea: {
              data: [
                [
                  {
                    yAxis: 70,
                  },
                  {
                    yAxis: 40,
                  },
                ],
              ],
              silent: true,
            },
          },
        ],
        dataset: {
          dimensions: ["time", "value"],
          source: [],
        },
      },
      pickerOptions: {},
      historyLine: null,
    };
  },
  created() {
    window.addEventListener("resize", this.chartsResize);
  },
  mounted() {
    this.init();
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.chartsResize);
  },
  methods: {
    init() {
      this.historyLine = this.$echarts.init(
        document.getElementById("historyLine")
      );
      this.$refs.klTable.searchData();
    },
    getTableData(params, sortStr) {
      let form = { ...params };
      form.equipmentId = this.currentDevice.id;
      form.mark = this.currentAppInfo.appCode;
      getYCRealTimeApi(form)
        .then((res) => {
          let data = res.data || [];
          data.map((i) => {
            i.id = i.paramId;
          });
          // let total = res.data.total || 0;
          this.$set(this.actualSeting, "tableData", data);
          if (data.length > 0) {
            this.currentLine = data[0];
            this.changeTime(1);
            this.getLineData();
            this.$refs.klTable.radioSelect(data[0]);
          }
          // this.$set(this.actualSeting, "totalNumber", total);
        })
        .catch((e) => {
          this.$set(this.actualSeting, "tableData", []);
          this.setLineOption([]);

          // this.$set(this.actualSeting, "totalNumber", 0);
        });
    },
    getLineData() {
      let form = {};
      this.LimitDateTime(); //做日期范围限制
      form = {
        code: this.currentLine.code,
        monitor:this.currentLine.monitor,
        startTime: new Date(this.historyStartTime).getTime(),
        endTime: new Date(this.historyEndTime).getTime(),
        type:this.type
      };
      getYCHistoryApi(form)
        .then((res) => {
          let data = res.data || [];
          this.setLineOption(data);
        })
        .catch((e) => {
          this.setLineOption([]);
        });
    },
    //获取范围
    getScope() {
      getScopeApi(this.currentLine.paramId).then((res) => {
        let data = res.data;
        this.currentLine.highLimit = data.highLimit || 0;
        this.currentLine.lowLimit = data.lowLimit || 0;
      });
    },
    setLineOption(data) {
      this.historyLine.clear();
      let option = {
        xAxis: {
          type: "category",
        },
        yAxis: {
          type: "value",
          name: "单位：" + this.currentLine.unit,
          axisLine: {
            show: true,
          },
        },
        tooltip: {
          trigger: "axis",
          textStyle: {
            align: "left",
          },
          formatter: function (params) {
            let item = params[0];
            let value = item.value;
            let result =
              value.sensorName +
              "<br/>时间：" +
              value.timeX +
              "<br/>数值：" +
              value.valueY;
            return result;
          },
        },
        series: [
          {
            type: "line",
            showSymbol: false,
            markArea: {
              data: [
                [
                  {
                    yAxis: this.currentLine.highLimit,
                  },
                  {
                    yAxis: this.currentLine.lowLimit,
                  },
                ],
              ],
              silent: true,
            },
          },
        ],
        dataset: {
          dimensions: ["timeX", "valueY"],
          source: data,
        },
      };
      this.historyLine.setOption(option);
    },
    //修改历史查询时间
    changeTime(num) {
      this.changeTimeBtn = num;
      if (num==7) {
        this.type = "day";
      } else {
        this.type = "hour";
      }
      let lastTime = this.currentLine.time;
      if (lastTime) {
        this.historyEndTime = lastTime;
        let endDate = this.$utils.countDate(lastTime, num, "sub");
        this.historyStartTime = endDate;
        this.getLineData();
      }
    },
    changeCustomTime(val) {
      if (val) {
        this.changeTimeBtn = "0";
        this.historyEndTime = val[1];
        this.historyStartTime = val[0];
      } else {
        this.changeTimeBtn = "1";
      }
      this.getLineData();
    },
    chartsResize() {
      this.historyLine.resize();
    },
    initCharts() {
      let option = this.getEchartOption();
      this.ganttChart.clear();
      this.ganttChart.setOption(option);
    },
    LimitDateTime() {
      let date = this.currentLine.time;
      date = new Date(date).valueOf();
      this.pickerOptions = {
        disabledDate(time) {
          return time.getTime() > date; //Date.now() - 3600 * 1000 * 24
        },
      };
    },
  },
};
</script>
<style lang="less" scoped>
.monitoring {
  display: flex;
  flex-flow: wrap nowrap;
  .monitoringRight,
  .monitoringLeft {
    height: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 15px;
  }
  .monitoringLeft {
    width: 50%;
  }
  .monitoringRight {
    width: 50%;
    margin-left: 15px;
  }
  .topTitle {
    display: flex;
    flex-flow: wrap nowrap;
    justify-content: space-between;
  }
  .monitoringTitle {
    width: auto;
    display: inline-block;
    font-size: 14px;
    text-align: left;
    font-weight: bolder;
    border-left: 3px solid @kr-elementUI-color;
    padding-left: 5px;
  }
  .timeDiv {
    font-size: 14px;
    color: #a8a8a8;
  }
  .content {
    margin-top: 15px;
  }
  .tableContent {
    // height: calc(100% - 60px);
    height: 100%;
  }
  .lineConditions {
    line-height: 40px;
    text-align: left;
    .chooseTime {
      min-width: 240px;
    }
    .chooseTime + .customTimeDiv {
      margin-left: 10px;
    }
    .el-button--plain {
      height: 30px;
    }
    .active {
      background-color: @kr-elementUI-color;
      color: @kr-main-bgcolor;
      border: none;
    }
  }
  .historyLine {
    height: 500px;
  }
  .customTimeDiv {
    min-width: 405px;
    display: inline-block;
    .el-date-editor--datetimerange.el-input,
    .el-date-editor--datetimerange.el-input__inner {
      width: 345px;
      padding: 2px 5px;
    }
    /deep/.el-date-editor .el-range__icon,
    /deep/.el-date-editor .el-range-separator,
    /deep/.el-date-editor .el-range__close-icon {
      line-height: 23px;
    }
    .el-input__inner {
      height: 30px;
      line-height: 30px;
    }
  }
}
</style>
